package com.qiku.web.servlet;

import com.qiku.base.BaseServlet;
import com.qiku.dao.UserDao;
import com.qiku.dao.impl.UserDaoImpl;
import com.qiku.pojo.Resource;
import com.qiku.pojo.User;
import com.qiku.service.ResourceService;
import com.qiku.service.impl.ResourceServiceImpl;
import com.qiku.utils.FileUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/resource")
public class ResourceServlet extends BaseServlet {

    private final ResourceService resourceService = new ResourceServiceImpl();

    //根据资源名或者上传用户名、资源类型查询资源
    public void findByNameOrUserName(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String resourceName = req.getParameter("resourceName");
            String userName = req.getParameter("userName");
            String type = req.getParameter("type");
            String resultJSON = resourceService.findByNameOrUserName(resourceName, userName, type);
//            System.out.println("resourceName:" + resourceName);
//            System.out.println("userName:" + userName);
//            System.out.println(resultJSON);
            resp.getWriter().print(resultJSON);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件类型 查询 文件
     *
     * @param req
     * @param resp
     */
    public void findResourceByType(HttpServletRequest req, HttpServletResponse resp) {
        try {
//            前端获取文件类型
            String type = req.getParameter("type");
            String resourceByType = resourceService.findResourceByType(type);
//            回显前端
            resp.getWriter().println(resourceByType);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //查询资源信息列表
    public void findResourceList(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String is_num = req.getParameter("is_num");
            int num;
            if (is_num != null) {
                num = Integer.parseInt(is_num);
            } else {
                num = 1;
            }
            String result = resourceService.findResourceList(num);
            resp.getWriter().println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 逻辑删除资源
     * @param req
     * @param resp
     */
    public void deleteResource(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String resource_id = req.getParameter("resource_id");
            String result = resourceService.deleteResource(resource_id);
            resp.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 逻辑恢复资源
     * @param req
     * @param resp
     */
    public void recoverResource(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String resource_id = req.getParameter("resource_id");
            String result = resourceService.recoverResource(resource_id);
            resp.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件，储存在本地，向数据库插入文件数据
     * test
     *
     * @param req  HttpServletRequest
     * @param resp HttpServletResponse
     */
    public void UpdateResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取用户对象
        HttpSession session = req.getSession();
        //将储存的 Session 转换为 user 对象
        User user = (User) session.getAttribute("user");
        // 判断 user 是否为空 为空进入测试状态 从数据库里查询一个用户用于测试
        if (user == null) {
            UserDao userDao = new UserDaoImpl();
            user = userDao.findUserById(1);
//            System.out.println("测试状态 当前上传资源的用户id为" + user.getId());
        }
//        System.out.println("resource 当前用户：" + user);
        try {
            // 创建磁盘工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建文件上传的核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 判断该表单是否是文件上传表单
            boolean multipartContent = upload.isMultipartContent(req);

//            System.out.println("multipartContent: " + multipartContent);
            if (multipartContent) {
                // 遍历文件项集合
                // 解析request -- 获得文件集合
                List<FileItem> list = upload.parseRequest(req);
                if (list != null) {
                    for (FileItem item : list) {
                        // 判断普通表单项/文件上传项
                        if (item.isFormField()) {
                            // 普通表单项
                            String fieldName = item.getFieldName();//获取name属性值
                            // 由于全局过滤器已经将req的编码格式设置为utf-8 为了防止乱码以utf-8 的编码获取数据
                            String fieldValue = item.getString("utf-8");//获取value属性的值
//                            System.out.println("name = " + fieldName);
//                            System.out.println("value = " + fieldValue);
                        } else {
                            // 获取文件名
                            String fileName = item.getName();
                            System.out.println(fileName);
                            // 获取输入流 获取输出流
                            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
                            //截取文件名获取文件类型
                            String ImgUrl;
                            //准备资源图标路径
                            //判断资源类型
                            if (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") ||
                                    type.equalsIgnoreCase("bmp") || type.equalsIgnoreCase("gif") ||
                                    type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("svg") ||
                                    type.equalsIgnoreCase("raw") || type.equalsIgnoreCase("ico")
                            ) {
                                ImgUrl = "uploadImg/img.png";

                            } else if (
                                    type.equalsIgnoreCase("mp3") || type.equalsIgnoreCase("flac") ||
                                            type.equalsIgnoreCase("acc") || type.equalsIgnoreCase("wav") ||
                                            type.equalsIgnoreCase("midi")
                            ) {
                                ImgUrl = "uploadImg/music.png";
                            } else if (
                                    type.equalsIgnoreCase("txt") || type.equalsIgnoreCase("md") ||
                                            type.equalsIgnoreCase("pdf") || type.equalsIgnoreCase("doc") ||
                                            type.equalsIgnoreCase("docx") || type.equalsIgnoreCase("rtf")
                            ) {
                                ImgUrl = "uploadImg/text.png";
                            } else if (
                                    type.equalsIgnoreCase("mp4") || type.equalsIgnoreCase("avi") ||
                                            type.equalsIgnoreCase("mkv") || type.equalsIgnoreCase("flv") ||
                                            type.equalsIgnoreCase("ogg") || type.equalsIgnoreCase("m4v") ||
                                            type.equalsIgnoreCase("mov") || type.equalsIgnoreCase("rmvb")
                            ) {
                                ImgUrl = "uploadImg/video.png";
                            } else if (
                                    type.equalsIgnoreCase("zip") || type.equalsIgnoreCase("7z") ||
                                            type.equalsIgnoreCase("rar") || type.equalsIgnoreCase("exe")
                            ) {
                                ImgUrl = "uploadImg/zip.png";
                            } else {
                                ImgUrl = "null";
                            }

                            if (!ImgUrl.equals("null")) {
                                InputStream in = item.getInputStream();
                                //获取项目根路径
                                String realPath = this.getServletContext().getRealPath("/");
                                // 输出路径表示
//                                System.out.println("项目部署路径(realPath)：" + realPath);
                                // 截取路径到webapps
                                String webapps = realPath.substring(0, realPath.indexOf("ResourceBundleSite"));
//                                System.out.println("webapps:" + webapps);
                                String outUrl = webapps + "upload";
//                                System.out.println("文件复制路径(outUrl) :" + outUrl);
                                // 图片上传到tomcat服务器
                                FileUtils fileUtils = new FileUtils();
                                Resource resource = fileUtils.copyFile(in, fileName, outUrl);

                                resource.setImg_url(ImgUrl);
                                resource.setUploader_id(user.getId());
                                String newFileName = resource.getId() + "_" + fileName;
                                //拼接使用uuid拼接文件名 保证文件名的唯一性
                                resource.setFile_url("localhost:8080/upload/" + newFileName);
//                                    resource.setUploader_id(1);
                                //插入文件数据
                                int i = resourceService.updateResource(resource);
                                if (i > 0) {
                                    req.setAttribute("fileMsg", "上传成功");
                                } else {
                                    req.setAttribute("fileMsg", "文件上传失败！！！");
                                }
                            } else {
                                req.setAttribute("fileMsg", "文件类型不支持");
                            }
                            //无论结果如何 转发消息
                            req.getRequestDispatcher("resourceUpload.jsp").forward(req, resp);
                        }
                    }
                }
            }
            // 判断普通表单项/ 文件上传项

        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

}
